package com.vmove.childtrain.activity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.jaygoo.widget.OnRangeChangedListener;
import com.jaygoo.widget.RangeSeekBar;
import com.vmove.childtrain.R;
import com.vmove.childtrain.common.Constants;
import com.vmove.childtrain.db.dao.LightDao;
import com.vmove.childtrain.db.entity.Light;
import com.vmove.childtrain.fragment.DegreeDialog_lesson3;
import com.vmove.childtrain.protocol.CommandType;
import com.vmove.childtrain.protocol.LightCMD;
import com.vmove.childtrain.protocol.detail.LightCMD_Close;
import com.vmove.childtrain.protocol.detail.LightCMD_Close_All;
import com.vmove.childtrain.protocol.detail.LightCMD_Open;
import com.vmove.childtrain.utils.ToastUtils;
import com.vmove.childtrain.utils.UIUtils;
import com.vmove.childtrain.view.MyCheckBox;
import com.vmove.childtrain.view.Panel;
import com.vmove.childtrain.view.interpolator.EasingType;
import com.vmove.childtrain.view.interpolator.ExpoInterpolator;
import com.vmove.childtrain.view.media.PlayView;

import java.sql.SQLException;
import java.util.List;
import java.util.Random;
import java.util.Vector;

import androidx.fragment.app.FragmentManager;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 课程3 寻找宝石
 * 四个灯，固定亮第一个后，从剩余3个中随机选择一个亮
 */
public class Lesson3Activity extends BaseLessonActivity {

    @BindView(R.id.playView)
    PlayView playView;
    @BindView(R.id.ib_show)
    ImageButton ibShow;

    @BindView(R.id.cb_lightNum)
    MyCheckBox cbLightNum;
    @BindView(R.id.seekbar_lightNum)
    RangeSeekBar seekbarLightNum;
    @BindView(R.id.cb_lightColor)
    MyCheckBox cbLightColor;
    @BindView(R.id.cb_userNum)
    MyCheckBox cbUserNum;
    @BindView(R.id.seekbar_userNum)
    RangeSeekBar seekbarUserNum;
    @BindView(R.id.cb_time)
    MyCheckBox cbTime;
    @BindView(R.id.seekbar_time)
    RangeSeekBar seekbarTime;
    @BindView(R.id.cb_stepNum)
    MyCheckBox cbStepNum;
    @BindView(R.id.seekbar_stepNum)
    RangeSeekBar seekbarStepNum;
    @BindView(R.id.tv_timeCountDown)
    TextView tvTimeCountDown;

    byte color1 = LightCMD.Color.GREEN.getByte();
    byte color2 = LightCMD.Color.RED.getByte();
    @BindView(R.id.rg_color)
    RadioGroup rgColor;
    @BindView(R.id.startLayout)
    FrameLayout startLayout;
    private LightDao lightDao;
    /**
     * 第二步的灯集合
     */
    private Vector<Integer> secondLights;
    private List<Light> allLights;
    private boolean isStart = false;
    private boolean isShow = false;
    private Random random;
    /**
     * 亮灯指令 检测模式：都检测  时长：永不超时
     */
    private LightCMD lightCMD;
    /**
     * 首次亮灯编号
     */
    private int firstLightId = 1;
    private int lightNum=4;
    /**
     * 循环次数
     */
    private int cycleNum = 5;
    private int stepCount = 0;
    private int timeCost=0;
    private FragmentManager fragmentManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lesson3);
        ButterKnife.bind(this);
        initData();
        initView();
        initSettings();
    }

    private void initData() {
        secondLights = new Vector<>();
        lightDao = new LightDao(this);
        for (int i = firstLightId + 1; i < firstLightId + 4; i++) {
            secondLights.add(i);
        }
        random = new Random();
        try {
            allLights = lightDao.getAllLights();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        fragmentManager = getSupportFragmentManager();
        initProtocolCmd();
    }

    private void initView() {
        cbStepNum.setIntValue(cycleNum);
        seekbarLightNum.setValue(4f);
        seekbarStepNum.setValue(5f);
        seekbarLightNum.setOnRangeChangedListener(seekBarChangeListener);
        seekbarStepNum.setOnRangeChangedListener(seekBarChangeListener);
        seekbarTime.setOnRangeChangedListener(seekBarChangeListener);
        seekbarUserNum.setOnRangeChangedListener(seekBarChangeListener);
        rgColor.setOnCheckedChangeListener(colorCheckChangeListener);
    }

    private RadioGroup.OnCheckedChangeListener colorCheckChangeListener = new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            switch (checkedId) {
                case R.id.rb_color_hong:
                    color2 = LightCMD.Color.RED.getByte();
                    cbLightColor.setText("红");
                    break;
                case R.id.rb_color_lv:
                    color2 = LightCMD.Color.GREEN.getByte();
                    cbLightColor.setText("绿");
                    break;
                case R.id.rb_color_lan:
                    color2 = LightCMD.Color.BLUE.getByte();
                    cbLightColor.setText("蓝");
                    break;
                case R.id.rb_color_qing:
                    color2 = LightCMD.Color.QING.getByte();
                    cbLightColor.setText("青");
                    break;
                case R.id.rb_color_zi:
                    color2 = LightCMD.Color.PURPLE.getByte();
                    cbLightColor.setText("紫");
                    break;
                case R.id.rb_color_huang:
                    color2 = LightCMD.Color.YELLOW.getByte();
                    cbLightColor.setText("黄");
                    break;
                case R.id.rb_color_bai:
                    color2 = LightCMD.Color.WHITE.getByte();
                    cbLightColor.setText("白");
                    break;
            }
        }
    };

    private OnRangeChangedListener seekBarChangeListener = new OnRangeChangedListener() {

        @Override
        public void onRangeChanged(RangeSeekBar view, float leftValue, float rightValue, boolean isFromUser) {
            int leftValueInt = (int) leftValue;
            switch (view.getId()) {
                case R.id.seekbar_lightNum:
                    cbLightNum.setIntValue(leftValueInt);
                    seekbarLightNum.setIndicatorText(leftValueInt + "个");
                    break;
                case R.id.seekbar_userNum:
                    cbUserNum.setIntValue(leftValueInt);
                    seekbarUserNum.setIndicatorText(leftValueInt + "人");
                    break;
                case R.id.seekbar_time:
                    cbTime.setIntValue(leftValueInt);
                    seekbarTime.setIndicatorText(leftValueInt + "分钟");
                    break;
                case R.id.seekbar_stepNum:
                    cycleNum = leftValueInt;
                    cbStepNum.setIntValue(leftValueInt);
                    seekbarStepNum.setIndicatorText(leftValueInt + "步");
                    break;
            }
        }

        @Override
        public void onStartTrackingTouch(RangeSeekBar view, boolean isLeft) {

        }

        @Override
        public void onStopTrackingTouch(RangeSeekBar view, boolean isLeft) {

        }
    };

    @OnClick(R.id.playView)
    public void onViewClicked(View view) {
        if (!isStart) {//开始
            startRun();
        } else {//停止
            stopRun();
        }
    }

    @OnClick(R.id.ib_show)
    public void clickShowButton() {
        //正在执行 不允许预演
        if (isStart){
            return;
        }
        if (!isShow) {
            //show
            isShow = true;
            ibShow.setImageResource(R.drawable.hand_stop);
            //todo 开启预演
            writeSerialByte(new LightCMD_Open().setLightColor(color1).setLight(firstLightId).getBytes());
            for (Integer i : secondLights) {
                writeSerialByte(new LightCMD_Open().setLightColor(color2).setLight(i).getBytes());
            }
        } else {
            //close
            writeSerialByte(new LightCMD_Close().setLight(firstLightId).getBytes());
            for (Integer i : secondLights) {
                writeSerialByte(new LightCMD_Close().setLight(i).getBytes());
            }
            ibShow.setImageResource(R.drawable.hand_start);
            isShow = false;
        }
    }

    @Override
    public void startRun() {
        if (cycleNum <=0){
            ToastUtils.toastWarning(this, "步骤必须大于0", 0);
            playView.setChecked(false);
            return;
        }
        if (isShow){
            ToastUtils.toastWarning(this, "请先结束预演", 0);
            playView.setChecked(false);
            return;
        }
        super.startRun();
        isStart = true;
        //亮第一个灯
        stepCount = 0;
        timeCost=0;
        writeSerialByte(new LightCMD_Open().setLightColor(color1).setCheckMode(LightCMD.CheckMode.ALL.getByte())
                .setLight(firstLightId).getBytes());
    }



    private static final int MSG_STOP=3001;
    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case MSG_STOP:
                    stopRun();
                    //todo 弹窗显示成绩
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Override
    public void stopRun() {
        super.stopRun();
        isStart = false;
        playView.setChecked(false);
        //关闭灯
        for (int i=firstLightId;i<firstLightId+lightNum;i++){
            writeSerialByte(new LightCMD_Close().setLight(i).getBytes());
        }
        //todo 弹出成绩窗体
        DegreeDialog_lesson3 degreeDialog_lesson3 = new DegreeDialog_lesson3();
        Bundle bundle = new Bundle();
        bundle.putInt("success",stepCount);
        bundle.putInt("time", timeCost);
        bundle.putInt("faild", 0);
        degreeDialog_lesson3.setArguments(bundle);
        degreeDialog_lesson3.show(fragmentManager, "dialog3");
    }

    /**
     * 随机点亮一个灯,并指定颜色[第二个步骤]
     */
    public void lightOn(byte color) {
        stepCount++;
        int index = random.nextInt(3);
        //从灭灯序列中随机移除一个并返回
        Integer lightId = secondLights.get(index);
        int stepNo = stepCount % 255;
        writeSerialByte(lightCMD.setStepNum(stepNo).setLightColor(color).setLight(lightId).getBytes());
    }

    @Override
    public void onSerialReceivedData(byte[] data) {
        if (data.length < 6) {
            UIUtils.showToastSafe("数据长度错误,请检测使用环境");
            return;
        }
        if (data[5] == CommandType.COMMAND_LIGHT_R) {//亮灯触发回复
            if (isStart) {
                parseLightR(data);
            }
        }
    }

    private void parseLightR(byte[] data) {
        //触发的light
        int lightId = data[4] & 0xff;
        //触发耗时 ms
        int time = ((data[11] & 0xff) << 24) | ((data[10] & 0xff) << 16) | ((data[9] & 0xff) << 8) | (data[8] & 0xff);
        //触发源
        byte source = data[6];
        //步骤码
        int stepNumber = data[7] & 0xff;
        if (lightId == firstLightId) {
            //亮第二个灯
            lightOn(color2);
        } else {
            //触发了第二个灯
            //记录时间
            timeCost += time;
            //根据循环次数和定时时间判断是否重新开始一次
            if (stepCount < cycleNum) {
                //继续开始
                writeSerialByte(new LightCMD_Open().setLightColor(color1).setCheckMode(LightCMD.CheckMode.ALL.getByte())
                        .setLight(firstLightId).getBytes());
            } else {
                mHandler.obtainMessage(MSG_STOP).sendToTarget();
                /*UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        stopRun();
                    }
                });*/
            }
        }
    }

    @Override
    public String returnToolBarTitle() {
        return "";
    }

    //----------属性设置 start-------
    @BindView(R.id.rightPanel)
    Panel panel;
    @BindView(R.id.seekbar_lightBrightness)
    RangeSeekBar seekbarLightBrightness;
    @BindView(R.id.rg_color_after)
    RadioGroup rgColorAfter;
    @BindView(R.id.seekbar_time_after)
    RangeSeekBar seekbarTimeAfter;
    @BindView(R.id.seekbar_infrared_sensitivity)
    RangeSeekBar seekbarInfraredSensitivity;
    @BindView(R.id.seekbar_pat_sensitivity)
    RangeSeekBar seekbarPatSensitivity;
    @BindView(R.id.seekbar_lightTime)
    RangeSeekBar seekbarLightTime;
    @BindView(R.id.rg_checkmode)
    RadioGroup rgCheckmode;
    @BindView(R.id.rg_lightmode)
    RadioGroup rgLightmode;
    @BindView(R.id.rg_voicemode)
    RadioGroup rgVoicemode;
    @BindView(R.id.bt_save)
    Button btSave;

    private int lightBrightness = Constants.LIGHT_BRIGHTNESS;
    private int checkTimeAfter = 0;
    private int infraredSensitivity = Constants.INFRARED_SENSITIVITY;
    private int patSensitivity = Constants.PAT_SENSITIVITY;
    private int lightTime=5;//亮灯超时时间 默认5s
    private byte colorAfterCheck = LightCMD.Color.NULL.getByte();
    private byte checkMode = LightCMD.CheckMode.ALL.getByte();
    private byte voiceMode = LightCMD.VoiceMode.STARTVOICE.getByte();
    private byte lightMode = LightCMD.LightMode.NULL.getByte();
    //----------属性设置 end-------


    /*--------------属性设置初始化- start------------*/
    private void initSettings() {
        panel.setInterpolator(new ExpoInterpolator(EasingType.Type.OUT));
        seekbarPatSensitivity.setValue(patSensitivity);
        seekbarInfraredSensitivity.setValue(infraredSensitivity);
        seekbarLightBrightness.setValue(lightBrightness);
        seekbarTimeAfter.setValue(checkTimeAfter);
        seekbarLightTime.setValue(lightTime);

        seekbarLightBrightness.setOnRangeChangedListener(settingSeekBarChangeListener);
        seekbarTimeAfter.setOnRangeChangedListener(settingSeekBarChangeListener);
        seekbarInfraredSensitivity.setOnRangeChangedListener(settingSeekBarChangeListener);
        seekbarPatSensitivity.setOnRangeChangedListener(settingSeekBarChangeListener);
        seekbarLightTime.setOnRangeChangedListener(settingSeekBarChangeListener);

        rgColorAfter.setOnCheckedChangeListener(settingRadioButtonCheckChangeListener);
        rgCheckmode.setOnCheckedChangeListener(settingRadioButtonCheckChangeListener);
        rgLightmode.setOnCheckedChangeListener(settingRadioButtonCheckChangeListener);
        rgVoicemode.setOnCheckedChangeListener(settingRadioButtonCheckChangeListener);
    }

    @OnClick(R.id.bt_save)
    public void onSaveClicked() {
        initProtocolCmd();
        ToastUtils.toastSuccess(this, "保存成功！", 0);
    }

    /**
     * 初始化亮灯协议数据
     */
    private void initProtocolCmd() {
        lightCMD = new LightCMD();
        lightCMD.setLightBrightness(lightBrightness)
                .setFinalLightColor(colorAfterCheck)
                .setFinalTimeLast(checkTimeAfter)
                .setInfraredSensitivity(infraredSensitivity)
                .setPatSensitivity(patSensitivity)
                .setCheckMode(checkMode)
                .setLightFlash(lightMode)
                .setTimeLast(lightTime)
                .setLightVoice(voiceMode);
    }

    /**
     * 属性设置中的回调
     */
    private OnRangeChangedListener settingSeekBarChangeListener = new OnRangeChangedListener() {

        @Override
        public void onRangeChanged(RangeSeekBar view, float leftValue, float rightValue, boolean isFromUser) {
            int leftValueInt = (int) leftValue;
            switch (view.getId()) {
                case R.id.seekbar_lightBrightness:
                    lightBrightness = leftValueInt;
                    seekbarLightBrightness.setIndicatorText(leftValueInt + "");
                    break;
                case R.id.seekbar_time_after:
                    checkTimeAfter = leftValueInt;
                    seekbarTimeAfter.setIndicatorText(leftValueInt + "");
                    break;
                case R.id.seekbar_infrared_sensitivity:
                    infraredSensitivity = leftValueInt;
                    seekbarInfraredSensitivity.setIndicatorText(leftValueInt + "");
                    break;
                case R.id.seekbar_pat_sensitivity:
                    patSensitivity = leftValueInt;
                    seekbarPatSensitivity.setIndicatorText(leftValueInt + "");
                    break;
                case R.id.seekbar_lightTime:
                    lightTime = leftValueInt;
                    seekbarLightTime.setIndicatorText(leftValueInt + "");
                    break;
            }
        }

        @Override
        public void onStartTrackingTouch(RangeSeekBar view, boolean isLeft) {

        }

        @Override
        public void onStopTrackingTouch(RangeSeekBar view, boolean isLeft) {

        }
    };

    /**
     * 属性设置radiobutton 回调
     */
    private RadioGroup.OnCheckedChangeListener settingRadioButtonCheckChangeListener = new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            switch (checkedId) {
                case R.id.rb_color_hong_after:
                    colorAfterCheck = LightCMD.Color.RED.getByte();
                    break;
                case R.id.rb_color_lv_after:
                    colorAfterCheck = LightCMD.Color.GREEN.getByte();
                    break;
                case R.id.rb_color_lan_after:
                    colorAfterCheck = LightCMD.Color.BLUE.getByte();
                    break;
                case R.id.rb_color_qing_after:
                    colorAfterCheck = LightCMD.Color.QING.getByte();
                    break;
                case R.id.rb_color_zi_after:
                    colorAfterCheck = LightCMD.Color.PURPLE.getByte();
                    break;
                case R.id.rb_color_huang_after:
                    colorAfterCheck = LightCMD.Color.YELLOW.getByte();
                    break;
                case R.id.rb_color_bai_after:
                    colorAfterCheck = LightCMD.Color.WHITE.getByte();
                    break;
                case R.id.rb_color_null_after:
                    colorAfterCheck = LightCMD.Color.NULL.getByte();
                    break;
                case R.id.rb_checkmode_all:
                    checkMode = LightCMD.CheckMode.ALL.getByte();
                    break;
                case R.id.rb_checkmode_infrared:
                    checkMode = LightCMD.CheckMode.Infrared.getByte();
                    break;
                case R.id.rb_checkmode_pat:
                    checkMode = LightCMD.CheckMode.PAT.getByte();
                    break;
                case R.id.rb_lightmode_all:
                    lightMode = LightCMD.LightMode.ALLLIGHT.getByte();
                    break;
                case R.id.rb_lightmode_start:
                    lightMode = LightCMD.LightMode.STARTLIGHT.getByte();
                    break;
                case R.id.rb_lightmode_null:
                    lightMode = LightCMD.LightMode.NULL.getByte();
                    break;
                case R.id.rb_voicemode_check:
                    voiceMode = LightCMD.VoiceMode.SENSEVOICE.getByte();
                    break;
                case R.id.rb_voicemode_start:
                    voiceMode = LightCMD.VoiceMode.STARTVOICE.getByte();
                    break;
                case R.id.rb_voicemode_null:
                    voiceMode = LightCMD.VoiceMode.NULL.getByte();
                    break;
            }
        }
    };
    /*--------------属性设置初始化-end------------*/

}
